package com.example.common.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.example.common.enetiy.User;
import com.example.common.mapper.UserMapper;
import com.example.common.service.UserService;
import com.example.common.utils.Assert;
import com.example.common.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/10/30 21:37
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final RedisUtils redisUtils;

    @Override
    public User queryUserByLogin(String username, String password) {
        User user = userMapper.queryUserByLogin(username, password);
        Assert.notNull(user, "用户为空");
        return user;
    }

    @Override
    public String registerUser(String username, String password) {
        User user = userMapper.queryUserByRegister(username);
        Assert.isNull(user, "用户名称重复，请更换名称");

        String userId = UUID.randomUUID().toString();
        User registerUser = User.builder()
                .userId(userId)
                .nickname("default")
                .username(username)
                .password(password)
                .build();
        userMapper.addUser(registerUser);
        return userId;
    }

    @Override
    public Map<String, User> getUserMap() {
        String userMapJson = redisUtils.get("userMap");
        Map<String, User> userMap = null;
        if (userMapJson != null) {
            userMap = JSONObject.parseObject(userMapJson, new TypeReference<>() {
            });
        }

        if (userMap != null) {
            return userMap;
        }

        List<User> users = userMapper.queryAllUser();
        userMap = users.stream().collect(
                Collectors.toMap(
                        User::getUserId,
                        user -> user,
                        (a, b) -> b
                )
        );

        redisUtils.set("userMap", JSONObject.toJSONString(userMap), 1L, TimeUnit.HOURS);
        return userMap;
    }

}
